/**
 * @fileOverview Sausage.js
 *
 * @example
 *       var canvasContext = $$(document)('querySelectorAll', 'canvas')(0)('getContext', '2d')();
 *       $$(canvasContext, {fixedContext: true})
 *       ('fillStyle', '#eee')
 *       ('strokeStyle', 'blue')
 *       ('beginPath')
 *       ('moveTo', 10, 10)
 *       ('lineTo', 100, 10)
 *       ('lineTo', 100, 100)
 *       ('lineTo', 10, 100)
 *       ('lineTo', 10, 10)
 *       ('closePath')
 *       ('stroke')
 *       ('fill')
 *       (); // canvasContext
 *
 * // if browser supports __noSuchMethod__
 *
 *       var canvasContext = $$(document).querySelectorAll('canvas')(0).getContext('2d')();
 *       var result = $$(canvasContext, {fixedContext: true})
 *       .fillStyle('#eee')
 *       .strokeStyle('blue')
 *       .beginPath()
 *       .moveTo(10, 10)
 *       .lineTo(100, 10)
 *       .lineTo(100, 100)
 *       .lineTo(10, 100)
 *       .lineTo(10, 10)
 *       .closePath()
 *       .stroke()
 *       .fill()
 *       ();
 *
 * @see http://jsfiddle.net/azproduction/LUXwY/
 * 
 * @licence MIT
 * Copyright (C) 2011 by Milhail Davydov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author  azproduction
 * @version 1.0
 */
(function (window, Array, __undefined__, __function__, __object__, __nsm__) {

    var profileData = {},
    isProfiling = false,
    getProfile = function(method) {
        if (!profileData[method]) {
            profileData[method] = {
                calls: 0,
                time: 0
            };
        }
        return profileData[method];
    },
    noSuchMethodSupported = (function(a){
        try {
            a[__nsm__] = function(){};
            a.b();
            return true;
        } catch (e) {
            return false;
        }
    }({})),

    /**
     * typeof wrapper, IE and WebKit fix
     * 
     * @param object
     * @param [context=null]
     *
     * @returns {String}
     */
    getType = function (object) {
        var typeofObject = typeof object;
        // WebKit typeof RegExp fix
        if (object instanceof RegExp) {
            typeofObject = __object__;
        }
        // IE typeof DOM methods fix
        if ('v'=='\v' && ('' + object).match(/\[native code\]/)) {
            typeofObject = __function__;
        }
        return typeofObject;
    },

    /**
     * is Array
     * 
     * @param object
     *
     * @returns {Boolean}
     */
    isArray = function (object) {
        return object instanceof Array;
    },

    /**
     * JavaScript Sausage chain
     * 
     * @param {Object}  context
     * @param {Object}  [options]
     * @param {Boolean} [options.fixedContext=false]
     * @param {Boolean} [options.returnValue=false]
     * @param {Mixed}   [options.lastContext]
     *
     * @returns {Function} Sausage
     */
    Sausage = function (context, options) {
        /**
         * @param {Function|String} method
         * @param {Mixed}           [param...]
         */
        function processor(method, param /*[, arguments, ...]*/) {
            var dt, currentProfile;
            switch (getType(method)) {
                case __function__: // Call method as a function with context argument
                    /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile('[anonymous function]'));
                    options.lastContext = method(context);
                    /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                    if (!options.fixedContext) {
                        context = options.lastContext;
                    }
                    break;
                case __undefined__: // No method passed - Continue Sausage or return value
                    if (options.returnValue) {
                        return Sausage(context, options);
                    } else {
                        if (getType(options.lastContext) !== __undefined__) {
                            return options.lastContext;
                        } else {
                            return context;
                        }
                    }
                case __object__: // Object or Array passed
                    if (isArray(method) && getType(context) === __function__) {
                        // It's Array and context - function. Call context with arguments in method
                        /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile('[context call]'));
                        options.lastContext = context.apply(context, method);
                        /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                        if (!options.fixedContext) {
                            context = options.lastContext;
                        }
                    } else {
                        // Bulk edit
                        var index, value;
                        for (index in method) {
                            value = method[index];
                            if (!isArray(value)) {
                                value = [value];
                            }
                            value.unshift(index);
                            processor.apply(this, value);
                        }
                    }
                    break;
                default: // Number or String
                    if (getType(context[method]) === __function__) { // If typeof argument's method - function; Call it
                        /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile(method));
                        options.lastContext = context[method].apply(context, Array.prototype.slice.call(arguments, 1));
                        /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                        if (!options.fixedContext) {
                            context = options.lastContext;
                        }
                    } else if (getType(param) !== __undefined__) { // if first parameter not undefined - assign
                        /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile(method));
                        context[method] = param;
                        /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                    } else { // if no paremeters passed - switch context
                        /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile('[switching context]'));
                        options.lastContext = context[method];
                        /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                        if (!options.fixedContext) {
                            context = options.lastContext;
                        }
                    }
            }
            // Continue Sausage or return value
            if (options.returnValue) {
                if (getType(options.lastContext) !== __undefined__) {
                    return options.lastContext;
                } else {
                    return context;
                }
            } else {
                return Sausage(context, options);
            }
        };

        // __noSuchMethod__ trick
        if (noSuchMethodSupported) {
            processor[__nsm__] = function (method, args) {
                var param = args[0], dt, currentProfile;
                if (getType(context[method]) === __function__) { // If typeof argument's method - function; Call it
                    /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile(method));
                    options.lastContext = context[method].apply(context, args);
                    /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                    if (!options.fixedContext) {
                        context = options.lastContext;
                    }
                } else if (getType(param) !== __undefined__) { // if first parameter not undefined - assign
                    /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile(method));
                    context[method] = param;
                    /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                } else { // if no paremeters passed - switch context
                    /* Profiler */ isProfiling && (dt = new Date, currentProfile = getProfile('[switching context]'));
                    options.lastContext = context[method];
                    /* Profiler */ isProfiling && (currentProfile.calls++, currentProfile.time += new Date - dt);
                    if (!options.fixedContext) {
                        context = options.lastContext;
                    }
                }

                // Continue Sausage or return value
                if (options.returnValue) {
                    if (getType(options.lastContext) !== __undefined__) {
                        return options.lastContext;
                    } else {
                        return context;
                    }
                } else {
                    return Sausage(context, options);
                }
            };
        }
        return processor;
    },

    /**
     * JavaScript Sausage Maker chain
     *
     * Validates values and proxies all to Sausage
     *
     * @param {Object}  context
     * @param {Object}  [options]
     *
     * @returns {Function} Sausage
     */
    SausageMaker = function (context, options) {
        // Define options once
        options = options || {};
        options.fixedContext = options.fixedContext || false;
        options.returnValue = options.returnValue || false;
        
        // Init Sausage
        return Sausage(context, options);
    };

    /**
     * Starts profiler
     */
    SausageMaker.profile = function () {
        isProfiling = true;
        profileData = {};
    };

    /**
     * Stops profiler
     *
     * @returns {Object} profile data
     */
    SausageMaker.profileEnd = function () {
        isProfiling = false;
        return profileData;
    };

    // Export Sausage
    window.$$ = window.Sausage = SausageMaker;
}(window, Array, 'undefined', 'function', 'object', '__noSuchMethod__'));